package com.orangelife.arenasdk.util;

import android.util.Base64;

import java.security.GeneralSecurityException;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * <p>
 * Created by 吴格非 on 2016-10-9.
 * <p>
 *
 * @author 吴格非
 * @since v1.0.0
 */

public class AesUtil {

    public static String encrypt(String crypto, String content) throws Exception {
//        String key = "1234567812345678";//AES秘钥
        String ivParameter = "1234567812345678";
        String charset = "UTF-8";
        String fullAlg = "AES/CBC/PKCS5Padding";
        Cipher cipher = Cipher.getInstance(fullAlg);
        IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
//        SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.decodeBase64(key.getBytes()), "AES");//会导致长度错误
        SecretKeySpec secretKeySpec = new SecretKeySpec(crypto.getBytes(), "AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, iv);
        byte[] encryptBytes = cipher.doFinal(content.getBytes(charset));
        byte[] bytes = Base64.encode(encryptBytes, 0);
        String s = new String(bytes);
        return s;
    }

    /**
     * 初始向量的方法, 全部为0. 这里的写法适合于其它算法,针对AES算法的话,IV值一定是128位的(16字节).
     *
     * @param fullAlg
     * @return
     * @throws GeneralSecurityException
     */
    private static byte[] initIv(String fullAlg) throws GeneralSecurityException {
        Cipher cipher = Cipher.getInstance(fullAlg);
        int blockSize = cipher.getBlockSize();
        byte[] iv = new byte[blockSize];
        for (int i = 0; i < blockSize; ++i) {
            iv[i] = 0;
        }
        return iv;
    }
}
